package service

import (
	"teacher-helper/dao"
	"teacher-helper/models"
	"teacher-helper/models/request"
)

func AddOneMajor(major models.SysMajor) error {
	return dao.DB.Create(&major).Error
}

func GetMajorList(queryInfo request.QueryInfo) (majors []models.SysMajor, total int, err error) {
	if queryInfo == (request.QueryInfo{}){
		err = dao.DB.Find(&majors).Error
		total = len(majors)
		return
	}
	if queryInfo.Query == "" {
		if err = dao.DB.Model(&models.SysMajor{}).Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Preload("Department").Find(&majors).Error
	} else {
		if err = dao.DB.Model(&models.SysMajor{}).Where("name like ?", "%"+queryInfo.Query+"%").Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Where("name like ?", "%"+queryInfo.Query+"%").Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Preload("Department").Find(&majors).Error
	}
	return
}

func GetRoleMajor(major_id int) (majorList []models.SysMajor, err error) {
	if major_id == 0{
		err = dao.DB.Find(&majorList).Error
	}else {
		err = dao.DB.Where(&models.SysMajor{ID:major_id}).Find(&majorList).Error
	}
	return
}

func GetMajorMap() (major_map map[int]string, err error) {
	var majors []models.SysMajor
	major_map = make(map[int]string)
	err = dao.DB.Find(&majors).Error
	for _, major := range majors{
		major_map[major.ID] = major.Name
	}
	return
}

func UpdateMajor(major models.SysMajor) error {
	return dao.DB.Model(&models.SysMajor{}).Where(&models.SysMajor{ID:major.ID}).Updates(&models.SysMajor{Name:major.Name,DepartmentID:major.DepartmentID,Level:major.Level}).Error
}

func DeleteMajor(major_id int) error {
	return dao.DB.Delete(&models.SysMajor{ID:major_id}).Error
}

